package ai.people.core.security.config;

import ai.people.core.security.extractor.TokenValueExtractor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 自定义令牌器
 *
 * @author yuanqinglong
 * @date 2022/6/2 17:35
 */
@Slf4j
@RequiredArgsConstructor
public class CustomizeTokenExtractor extends BearerTokenExtractor {

    /**
     * 令牌值提取器
     */
    private final List<TokenValueExtractor> tokenValueExtractors;


    /**
     * 重新提取token策略，从cookie中获取token
     *
     * @param request 请求
     * @return {@link Authentication}
     */
    @Override
    public Authentication extract(HttpServletRequest request) {
        for (TokenValueExtractor tokenValueExtractor : tokenValueExtractors) {
            String tokenValue = tokenValueExtractor.extractToken(request);
            if (tokenValue != null) {
                return new PreAuthenticatedAuthenticationToken(tokenValue, "");
            }
        }
        log.warn("token为空");
        return null;
    }
}
